Code
library(tidyverse)
library(janitor)Tony Duan
August 12, 2023
New column names=old column name
change all column to upper
[1] "FIRST_COLUMN" "SECOUND_COLUMN" "SOMETHING_ELSE"
change all column end with ’column ’to upper
[1] "FIRST_COLUMN" "SECOUND_COLUMN" "something_else"
change all column end with ‘column’ from _ to .
https://www.youtube.com/watch?v=MhCTjM3xHZY
---
title: "Handling dataframe columns names"
author: "Tony Duan"
date: "2023-08-12"
categories: [packages]
execute:
warning: false
error: false
format:
html:
toc: true
code-fold: show
code-tools: true
number-sections: true
code-block-bg: true
code-block-border-left: "#31BAE9"
---
# clear columns names with clean_names()
```{r}
library(tidyverse)
library(janitor)
```
```{r}
#| code-fold: true
# make data001
data001=data.frame(v1=c(1,2,3),V2=seq(3),V3=seq(3))
colnames(data001) <- c('first Column', 'The secound','something_else')
```
```{r}
data001%>% names()
```
```{r}
data002=data001 %>% clean_names()
data002%>% names()
```
# change one column names
New column names=old column name
```{r}
data003=data002 %>% rename('secound_column'='the_secound')
data003%>% names()
```
# change multiple column names
change all column to upper
```{r}
data003 %>% rename_with(toupper) %>% names()
```
change all column end with 'column 'to upper
```{r}
data003 %>% rename_with(toupper,ends_with('column')) %>% names()
```
change all column end with 'column' from _ to .
```{r}
data003 %>% rename_with(~gsub('_','.',.x),ends_with('column')) %>% names()
```
# Reference
https://www.youtube.com/watch?v=MhCTjM3xHZY